import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.getters.token
    if (token) config.headers.Authorization = 'Bearer ' + token
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const { success, message, data } = response.data
    if (success) {
      // 业务正确
      return data
    } else {
      // 业务错误
      Message.error(message) // 提示错误
      return Promise.reject(message)
    }
  },
  async error => {
    // console.log('err' + error)
    console.dir(error)
    if (error.response && error.response.status === 401) {
      Message.error('token过期,请重新登录')
      // 清楚用户数据  token
      await store.dispatch('user/logout')
      // 挑战登录页面
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
